//
//  RCDTextFeidView.m
//  jsy
//
//  Created by  任辰东 on 2020/4/11.
//  Copyright © 2020 JSY. All rights reserved.
//

#import "RCDTextFeidView.h"
#import "RCDPadTextField.h"

@implementation RCDTextFeidViewModel

@end

@interface RCDTextFeidView ()<UITextFieldDelegate>
@property (nonatomic, strong) UIImageView *leftImgView;
@property (nonatomic, strong) UIImageView *rightImgView;
@property (nonatomic, strong) UILabel *titleLable;
@end

@implementation RCDTextFeidView

- (instancetype)initWithModel:(RCDTextFeidViewModel *)model
{
    if (self = [super init]) {
        
        _model = model;
        [self setupViews];
        [self setupLayout];
    }
    return self;
}

- (void)setupViews
{
    self.userInteractionEnabled = !_model.isNotEnable;
    
    _leftImgView = [UIImageView new];
    [_leftImgView setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    if (!IsEmpty(_model.leftImgPath)) {
        _leftImgView.image = UIImageWithName(_model.leftImgPath);
    }
    [self addSubview:_leftImgView];
    
    _titleLable = [UILabel new];
    [_titleLable setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    _titleLable.text = _model.leftTitle;
    if (_model.leftTitleFont) {
        _titleLable.font = _model.leftTitleFont;
    }else{
        _titleLable.font = UIFontSize(16);
    }

    if (_model.leftTitleColor) {
        _titleLable.textColor = _model.leftTitleColor;
    }else{
        _titleLable.textColor = UIColorFromHex(0x010101);
    }
    [self addSubview:_titleLable];
    WeakSelf
    RACChannelTo(self.titleLable, text) = RACChannelTo(self.model, leftTitle);
    RACChannelTo(self.titleLable, textColor) = RACChannelTo(self.model, leftTitleColor);
    //右边箭头双边
    RACChannelTerminal *channel1 = RACChannelTo(self.leftImgView, image);
    RACChannelTerminal *channel2 = RACChannelTo(self.model, leftImgPath);
    [[channel2 map:^id(NSString *value) {
        if (IsEmpty(value)) {
            return nil;
        }
        return UIImageWithName(value);
    }] subscribe:channel1];
    [channel1 subscribe:channel2];
//
//    [RACObserve(self.model, leftImgPath) subscribeNext:^(NSString * x) {
//        StrongSelf
//        if (IsEmpty(x)) {
//            self.leftImgView.image = UIImageWithName(x);
//        }
//    }];
    if (_model.isTextView) {
        _textView = [RCDPlaceholderTextView new];
        if (_model.placeholder) {
            _textView.placeholder = _model.placeholder;
        }else{
            _textView.placeholder = @" ";//暂时解决RCDPlaceholderTextView的bug！！！！！
        }
        _textView.placeholderColor = UIColorFromHex(0xcccccc);
        if (_model.contentColor) {
            _textView.textColor = _model.contentColor;
        }else{
            _textView.textColor = UIColorFromHex(0x010101);
        }
        _textView.backgroundColor = [UIColor clearColor];
        _textView.font = UIFontSize(16);
        _textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _textView.layer.masksToBounds = YES;
         [self addSubview:_textView];
        
        _textView.text = _model.content;//修复第一次给content赋值后，_textView经过后续的rac把content置空的bug
        
        RACChannelTerminal *modelTerminal = RACChannelTo(self.model, content);
        RACChannelTerminal *textChannel = RACChannelTo(self.textView, text);
        WeakSelf
        [[self.textView.rac_textSignal map:^id(NSString *value) {
            StrongSelf
            //z字数限制
            if (value.length > self.model.limitNum && self.model.limitNum > 0) {
                NSString *subString = [self.textView.text substringToIndex: self.model.limitNum];
                self.textView.text = subString;
                return subString;
            }
             return value;
        }] subscribe:modelTerminal];
        
        [modelTerminal subscribe:textChannel];
        
    }else{
        _textFeild = [UITextField new];
        _textFeild.backgroundColor = [UIColor clearColor];
        _textFeild.secureTextEntry = _model.secureTextEntry;
        if (_model.placeholder) {
            _textFeild.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_model.placeholder attributes:@{NSFontAttributeName : UIFontSize(16), NSForegroundColorAttributeName : UIColorFromHex(0xd4d3cf)}];
        }
        if (_model.contentColor) {
            _textFeild.textColor = _model.contentColor;
        }else{
            _textFeild.textColor = UIColorFromHex(0x010101);
        }
        if (_model.contentFont) {
            _textFeild.font = _model.contentFont;
        }else{
            _textFeild.font = UIFontSize(16);
        }
        _textFeild.keyboardType = _model.keyboardType;
        if (_model.keyboardType == UIKeyboardTypeDecimalPad || _model.keyboardType == UIKeyboardTypeNumberPad) {
            _textFeild.inputAccessoryView = [self addToolbar];
        }
        _textFeild.textAlignment = _model.alignment;
        if (_model.returnKeyType) {
            _textFeild.returnKeyType = _model.returnKeyType;
            _textFeild.delegate = self;
        }
        _textFeild.enablesReturnKeyAutomatically = YES;
        _textFeild.clearButtonMode = UITextFieldViewModeWhileEditing;
        [self addSubview:_textFeild];
        
        [_textFeild addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        
        RACChannelTo(self.textFeild, text) = RACChannelTo(self.model, content);
        
    }
    
    _rightImgView = [UIImageView new];
    [_rightImgView setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    if (!IsEmpty(_model.rightImgPath)) {
        _rightImgView.image = UIImageWithName(_model.rightImgPath);
    }
    [self addSubview:_rightImgView];
    
    //右边箭头双边
    RACChannelTerminal *channelA = RACChannelTo(self.rightImgView, image);
    RACChannelTerminal *channelB = RACChannelTo(self.model, rightImgPath);
    [[channelB map:^id(NSString *value) {
        if (IsEmpty(value)) {
            return nil;
        }
        return UIImageWithName(value);
    }] subscribe:channelA];
    [channelA subscribe:channelB];
    
    //是否可交互
    [RACObserve(self.model, isNotEnable) subscribeNext:^(NSNumber *isEnable) {
        self.userInteractionEnabled = !isEnable.boolValue;
    }];
    
    
    if (!IsEmpty(_model.rightImgPath)) {
        _textFeild.enabled = NO;
        self.isHighlight = YES;
    }
    
    //[self addBottomLine];
    
    
    CGFloat minHeight;
    CGFloat maxHeight;
    if (_model.minHeight > 0) {
        minHeight = _model.minHeight;
    }else{
        minHeight = 33;//默认(textview与self的上下边距为8， 33+8*2=49)
    }
    if (_model.maxHeight > 0) {
        maxHeight = _model.maxHeight;
    }else{
        maxHeight = 160;//默认
    }
    
//    WeakSelf
    [RACObserve(_textView, contentSize) subscribeNext:^(id x) {
        StrongSelf
        CGFloat h = self.textView.contentSize.height;
        if (h <= minHeight)
        {
            h = minHeight;
        }
        
        if (h > maxHeight) {
            h = maxHeight;
        }
        [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(h);
        }];
    }];
}

- (void)setupLayout
{
    if (self.model.isTextView) {
        
        [_leftImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(16);
            //            make.centerY.equalTo(self.mas_centerY);
            make.top.equalTo(self).offset(16);
            make.width.mas_equalTo(IsEmpty(_leftImgView.image)?0:_leftImgView.image.size.width);
        }];
        
        [_titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_leftImgView.mas_right).offset(IsEmpty(_titleLable.text)?0:6);
            //            make.centerY.equalTo(self.mas_centerY);
            make.top.equalTo(self).offset(16);
        }];
        
        [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_titleLable.mas_right).offset(6);
            make.top.equalTo(self).offset(8);
            make.bottom.equalTo(self).offset(-8);
            make.centerY.equalTo(self.mas_centerY);
        }];
    }else{
        
        [_leftImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(16);
            make.centerY.equalTo(self.mas_centerY);
            //        make.top.equalTo(self).offset(16);
            make.width.mas_equalTo(IsEmpty(_leftImgView.image)?0:_leftImgView.image.size.width);
        }];
        
        [_titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_leftImgView.mas_right).offset(IsEmpty(_titleLable.text)?0:6);
            make.centerY.equalTo(self.mas_centerY);
            //        make.top.equalTo(self).offset(16);
        }];
        [_textFeild mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_titleLable.mas_right).offset(6);
            make.top.bottom.equalTo(self);
            make.centerY.equalTo(self.mas_centerY);
        }];
    }
    
    [_rightImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mas_right).offset(-16);
        make.centerY.equalTo(self.mas_centerY);
        if (self.model.isTextView) {
            make.left.equalTo(_textView.mas_right).offset(0);
        }else{
            make.left.equalTo(_textFeild.mas_right).offset(6);
        }
        make.width.mas_equalTo(IsEmpty(_rightImgView.image)?0:_rightImgView.image.size.width);
    }];
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (_model.limitNum > 0) {
        if (textField.text.length >  _model.limitNum) {
            textField.text = [textField.text substringToIndex: _model.limitNum];
        }
    }
    
    if (self.textFieldCallBack) {
        self.textFieldCallBack(textField.text);
    }
    

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (self.didSearch) {
        self.didSearch(textField.text);
    }
    [textField resignFirstResponder];
    return YES;
    
}

- (UIToolbar *)addToolbar
{
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    toolbar.tintColor = [UIColor blackColor];
    toolbar.backgroundColor = [UIColor grayColor];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(textFieldDone)];
    [bar setTitleTextAttributes:@{NSFontAttributeName:UIBoldFontSize(18)} forState:UIControlStateNormal];
    toolbar.items = @[space, bar];
    return toolbar;
}

- (void)textFieldDone
{
    [self.textFeild resignFirstResponder];
}
@end
